package me.zxk.qwert_poetry.util;

import me.zxk.qwert_poetry.dto.response.Response;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "me.zxk.qwert_poetry.controller")
public class GlobalControllerHandler implements ResponseBodyAdvice<Object> {
    // TODO 统一错误码格式
    // 需要考虑：Api 错误、一般异常
    // 可以考虑用位运算
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ApiException.class)
    public Response<Void> handleApiConflict(ApiException e) {
        return new Response<Void>(e.getMessage(), e.getErrorCode());
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        System.out.println(request.getURI().getPath());
        String path = request.getURI().getPath();
        if (!path.startsWith("/api"))
            return body;
        else {
            if (body instanceof Response<?>)
                return body;
            else
                return new Response<Object>("ok", 0, body);
        }
    }
}